import React, { Component } from 'react'
import axios from "./utils/axios"

import Left from './components/Left'
import TabTitle from './components/TabTitle'
import TabCont from './components/TabCont'

export class App extends Component {
  constructor(props) {
    super(props)
  
    this.state = {
       list:[],   //全部数据
       activeId:"",   //高亮id
    }
  }

  // 请求数据 
  componentDidMount() {
    axios.get("/api/list").then( res => {
      res.data[0].flag = true;//默认右侧头部显示第一项
      this.setState({
        list: res.data,
        activeId: res.data[0].id, //默认第一个id
      })
    })
  }

  // 1）左侧点击高亮
  changeLeft(id) {
    let { list, activeId } = this.state;
    list.forEach( item => {
      if( item.id === id ) {
        item.flag = true;  //设置为true,用作右侧头部渲染
        activeId = item.id; //存当前的id
      }
    })

    // 重新赋值 
    this.setState({
      list,
      activeId: activeId 
    })
  }

  // 2）点击右侧头部 
  changeTitle(id) {
    let { list, activeId } = this.state;
    list.forEach( item => {
      if( item.id === id) {
        activeId = item.id
      }
    })
    // 重新赋值 
    this.setState({
      activeId: activeId
    })
  }

  // 3）点击删除
  delFn(id) {
    let { list } = this.state;
    list.forEach( item => {
      if( item.id === id) {
        item.flag = false
      }
    })
    // 重新赋值 
    this.setState({
      list: list
    })
  }


  render() {
    const { list, activeId } = this.state;
    return (
      <div className='App'>
        {/* 左侧内容  */}
        <Left 
        list = { list }
        activeId = { activeId }
        changeLeft = { this.changeLeft.bind(this)} //左侧点击事件
        ></Left>

        <div className='rightC'>
        {/* 右侧头部内容  */}
        <TabTitle
            list = { list }
            activeId = { activeId }
            changeTitle = { this.changeTitle.bind(this)} // 内容和高亮切换
            delFn = { this.delFn.bind(this)}
            ></TabTitle>
        <TabCont
        list = { list }
        activeId = { activeId }
        ></TabCont>
        </div>
       
      </div>
    )
  }
  
}

export default App